package com.anhdt.dao;

import com.anhdt.vo.CategoriesVO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CategoriesDAO extends BaseDAO {

    private static CategoriesDAO categoriesDAO;

    private CategoriesDAO() {
    }

    public static CategoriesDAO getInstance() {
        if (categoriesDAO == null) {
            categoriesDAO = new CategoriesDAO();
        }
        return categoriesDAO;
    }

   
    public List<CategoriesVO> getListCateByTopic(int idTopic) throws SQLException {
        List<CategoriesVO> list = new ArrayList<>();
        Connection conn =   connect.getConnnection();
        try {
            String sql = "Select * from categories where id_parent =?";
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setInt(1, idTopic);
            try (ResultSet res = stmt.executeQuery()) {
                while (res.next()) {
                    CategoriesVO tmp = new CategoriesVO();
                    int id = res.getInt("id");
                    String name = res.getString("cate_name");
                    tmp.setId(id);
                    tmp.setName(name);
                    list.add(tmp);
                }
            }
            return list;
        } catch (SQLException e) {
            e.getStackTrace();
        } finally {
            if(conn!=null) conn.close();
        }
        return list;

    }

    public CategoriesVO getCateDetail(int idCate) throws SQLException {
        CategoriesVO result = new CategoriesVO();
        String sql = "Select * from categories where id =?";

        Connection conn = connect.getConnnection();
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setInt(1, idCate);
        try (ResultSet res = stmt.executeQuery()) {
            while (res.next()) {
                result.setId(idCate);
                result.setName(res.getString("cate_name"));
                PostDAO post = PostDAO.getInstance();
                result.setListPost(post.getListPostByCateID(idCate));
            }
        }
        conn.close();
        return result;
    }
}
